<template>
    <el-dialog :visible.sync="addVisible" @close="$emit('update:addVisible',false)" width="70%" :show-close='false' :class="{'equipCheckDialog':true,'checkDialog':fromModel != 'dataEntry'}" :closeOnClickModal='false'>
        <span slot="title" class="dialog-title">
            仪器使用记录
            <el-button size="mini" @click="close" class="popupClose">关闭</el-button>
        </span>
        <el-tabs style="width:100%;"  v-model="equipTabsValue" type="card" v-if = "reload">
            <el-tab-pane v-for="(item,index) in equipArr" :label="item.name" :key="item.id + index"  :name="item.id" >
                <div class="equipform">
                    仪器使用记录
                    <el-button size="mini" @click="adduseBeans(item.use)" type="primary" style="float:right;margin-bottom:5px;"  v-if = "fromModel == 'dataEntry'">添加</el-button>
                    <el-table :data="item.use" style="width: 100%;" height = "120px" class="tableCon" size="mini">
                        <el-table-column label="序号" min-width="40px">
                            <template slot-scope="scope">
                                {{scope.$index+1}}
                            </template>
                        </el-table-column>
                        <el-table-column property="startDate" label="开机时间" min-width="100px" v-if = "fromModel == 'dataEntry'">
                            <template slot-scope="scope" >
                                <el-date-picker v-model="scope.row.startDate" type="datetime"  size="mini" style="width:100%;" placeholder="选择日期时间" format="yyyy-MM-dd HH:mm" value-format="yyyy-MM-dd HH:mm">
                                </el-date-picker>
                            </template>
                        </el-table-column>
                        <el-table-column property="startDate" label="开机时间" min-width="110px" :formatter = "formatterDate"  v-if = "fromModel != 'dataEntry'" >
				        </el-table-column>
                        <el-table-column property="endDate" label="关机时间" min-width="100px" v-if = "fromModel == 'dataEntry'">
                            <template slot-scope="scope">
                                <!--:picker-options="pickeroption" @focus = "dateChangeEndTime($event,scope.row)"-->
                                <el-date-picker v-model="scope.row.endDate" type="datetime" size="mini" style="width:100%;" placeholder="选择日期时间" format="yyyy-MM-dd HH:mm" value-format="yyyy-MM-dd HH:mm">
                                </el-date-picker>
                            </template>
                        </el-table-column>
                        <el-table-column property="endDate" label="关机时间" min-width="110px" :formatter = "formatterDate"  v-if = "fromModel != 'dataEntry'" >
				        </el-table-column>
                        <el-table-column property="temperature" label="温度(℃)" min-width="60px" >
                            <template slot-scope="scope">
                              <!-- temperature humidity-->
                                <el-input v-if = "fromModel == 'dataEntry'" size="mini"  style="width:100%;" v-model="scope.row.temperature" placeholder="温度" class="deal" oninput="this.value=this.value.replace(/[^0-9.]+/,'');"></el-input>
                                <span v-if = "fromModel != 'dataEntry'">{{scope.row.temperature}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column property="humidity" label="湿度(%)" min-width="60px">
                            <template slot-scope="scope">
                                <el-input size="mini" v-if = "fromModel == 'dataEntry'" style="width:100%;" v-model="scope.row.humidity" placeholder="温度" class="deal" oninput="this.value=this.value.replace(/[^0-9.]+/,'');"></el-input>
                                 <span v-if = "fromModel != 'dataEntry'">{{scope.row.humidity}}</span>
                           </template>
                        </el-table-column>
                        <el-table-column property="runStatus" label="状况" min-width="100px">
                            <template slot-scope="scope">
                                <el-input size="mini" style="width:100%;" v-model="scope.row.runStatus" placeholder="状况" v-if = "fromModel == 'dataEntry'"></el-input>
                                 <span v-if = "fromModel != 'dataEntry'">{{scope.row.runStatus}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" min-width="100px">
                            <template slot-scope="scope">
                                <el-button size="mini" @click="deleteUse(scope.$index,item.use)" type="text"  v-if = "fromModel == 'dataEntry'">删除</el-button>
                                <el-button size="mini" @click="getEuitpmentTemp(scope.row,item)" type="text">温控</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="equipTable">
                    <div style="height:30px;line-height:30px;">测试前检查</div>
                    <el-table :data="item.before" style="width: 100%;height:calc((100% - 70px)/2)" class="tableCon" size="mini" ref="multipleTable" v-if="reload">

                        <el-table-column label="序号" min-width="40px">
                            <template slot-scope="scope">
                                {{scope.$index+1}}
                            </template>
                        </el-table-column>
                        <el-table-column property="content" label="检查项" min-width="200px" :show-overflow-tooltip="true">
                        </el-table-column>
                        <el-table-column property="doPass" label="检查结果" min-width="150px">
                            <template slot-scope="scope">
                                <el-select v-model="scope.row.doPass" size="mini" clearable :disabled = " fromModel != 'dataEntry'">
                                    <el-option v-for="item in isPass" :key="item.value" :label="item.label" :value="item.value">
                                    </el-option>
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column property="remark" label="备注" min-width="100px">
                            <template slot-scope="scope">
                                 <el-input size="mini" v-model="scope.row.remark" v-if = " fromModel == 'dataEntry'"></el-input>
                                <span v-if = "fromModel != 'dataEntry'">{{scope.row.remark}}</span>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div style="height:30px;line-height:30px;">测试后检查</div>
                    <el-table :data="item.after" style="width: 100%;height:calc((100% - 70px)/2)" class="tableCon" size="mini" ref="multipleTable1" v-if="reload">

                        <el-table-column label="序号" min-width="40px">
                            <template slot-scope="scope">
                                {{scope.$index+1}}
                            </template>
                        </el-table-column>
                        <el-table-column property="content" label="检查项" min-width="200px" :show-overflow-tooltip="true">
                        </el-table-column>

                        <el-table-column property="doPass" label="检查结果" min-width="150px">
                            <!--{0 不通过 1 通过}-->
                            <template slot-scope="scope">
                                <el-select v-model="scope.row.doPass" size="mini" clearable :disabled = " fromModel != 'dataEntry'">
                                    <el-option v-for="item in isPass" :key="item.value" :label="item.label" :value="item.value">
                                    </el-option>
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column property="remark" label="备注" min-width="100px">
                            <template slot-scope="scope">
                                <el-input size="mini" v-model="scope.row.remark" v-if = " fromModel == 'dataEntry'"></el-input>
                                <span v-if = "fromModel != 'dataEntry'">{{scope.row.remark}}</span>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-tab-pane>
        </el-tabs>

        <span slot="footer" class="dialog-footer" v-if = "fromModel == 'dataEntry'">
            <el-button type="primary" size="mini" @click="subEquipInfo" :disabled="!isRepeat">确 定</el-button>
            <el-button size="mini" @click="close">取 消</el-button>
        </span>
        <equiptemp :addVisible.sync="equiptempShow" :equipmentId="equipmentId" :rowTime="rowTime"></equiptemp>
    </el-dialog>
</template>

<script>
import {
    mapState
} from 'vuex'
const equiptemp = () => import('./equiptemp.vue');
export default {
    data() {
        var that = this;
        return {
            equipPreUseList: [],
            equipUseList: [],
            isPass: [{
                value: false,
                label: '不通过'
            }, {
                value: true,
                label: '通过'
            }],
            preUseSelection: [], //使用前检查项
            afterUseSelection: [], //使用后检查项
            reload: true,

            equipForm: {
                startDate: "",
                endDate: "",
                temperature: "",
                humidity: "",
                runStatus: "",
            },
            equipRules: {
                startDate: [{
                    required: true,
                    message: '请选择开机时间',
                    trigger: 'change'
                }],
                endDate: [{
                    required: true,
                    message: '请选择关机时间',
                    trigger: 'change'
                }],
                temperature: [{
                    required: true,
                    message: '请填写温度',
                    trigger: 'blur'
                }],
                humidity: [{
                    required: true,
                    message: '请填写湿度',
                    trigger: 'blur'
                }],
                runStatus: [{
                    required: true,
                    message: '请填写状况',
                    trigger: 'blur'
                }],
            },
            hasEquip: null,
            pickerOptions: { //接样日期
                disabledDate(time) {
                    console.log(time)
                    if (that.equipForm.startDate != '') {
                        let startDate = new Date(that.equipForm.startDate);
                        return (time.getTime() < new Date(startDate).getTime() - 8.64e6);
                    }

                }
            },
            useBeans: [],
            equiptempShow: false,
            rowTime: {},
            equipArr: [],
            equipTabsValue:'',
            // pickeroption:this.dateChangeEndTime(),
            isRepeat:true,
        }
    },
    computed: {
        ...mapState(['typeQcSelect']),
        sampleTableHeight() {
            return 200
        },
    },
    components: {
        equiptemp
    },
    props: ['addVisible', 'equipmentId', 'testpanelData', 'editOrAdd', 'hasEquipUse','fromModel'],
    mounted() {
        this.$store.dispatch('dogetDictionary')
    },
    watch: {
      async addVisible(val, oldVal) {
           let arr = []
            if (val) {
                 // 组装仪器信息
                //主仪器
                var equipObj = { name: this.testpanelData.equipmentName, id: this.testpanelData.equipment,
                    use:[],
                    after:[],
                    before:[],
                    isMain:true,
                }
                this.equipArr.push(equipObj)
                this.equipTabsValue = this.equipArr[0].id;
                // 加入辅助仪器
                if (this.testpanelData.assistEquipment != undefined && this.testpanelData.assistEquipment != '' && this.testpanelData.assistEquipment != null) {
                  let res = await this.readEquipmentList()
                    var assistEquipment = JSON.parse(JSON.stringify(this.testpanelData.assistEquipment.split(";")))
                    for (var i in assistEquipment) { //辅助仪器分割的数字
                        for(var j in res.data){ //遍历所有的仪器，找到与辅助仪器对应的文字
                            if(assistEquipment[i] == res.data[j].equipment && !res.data[j].isMain){
                                var obj = {};
                                obj.id = assistEquipment[i]
                                obj.name = res.data[j].name;
                                obj.isMain = false;
                                obj.use = [];
                                obj.after = [];
                                obj.before = [];
                                this.equipArr.push(obj)

                            }
                        }
                    }
                }
                // 遍历查找仪器使用记录和测试前后检查项
                if (this.editOrAdd == 'edit' || this.fromModel != 'dataEntry') {
                    this.equipArr.map(async (i)=>{
                        let data = await this.readEquipmentUse(i)
                        console.log(data)
                        i.use = data.data.use;
                        i.after = data.data.after;
                        i.before = data.data.before;
                    })
                } else {
                    for(var i in this.equipArr){
                        this.getUsecheck(this.equipArr[i]);
                    }

                }
            }
        }
    },
    methods: {
        // 处理时间
        formatterDate(row, column, cellValue) {
            if(cellValue == '' || cellValue == undefined || cellValue == null){
                return ''
            }else{
                return cellValue.substring(0, 16)
            }

        },
        // 获取主仪器
		readEquipmentList() {
            return new Promise((resolve, reject) => {
                var data = {
                    id: this.testpanelData.detectability,
                }
                this.$http({
                    method: 'post',
                    apiUrl: '/technology/readEquipmentBeanList.htm',
                    params: data,
                    isJson: false
                }).then(res => {
                    if (res.code == 0) {
                        resolve(res)
                    }else{
                        reject(err)
                    }
                })
            });
		},
        adduseBeans(itemUse) {
            console.log(itemUse)
            itemUse.push({
                startDate: "",
                endDate: "",
                temperature: null,
                humidity: null,
                runStatus: "正常",
            });
        },
        deleteUse(index,itemUse) {
            itemUse.splice(index, 1)
        },
        getEquipInfo(tab){
        //    this.readEquipmentUse(tab.name)
        },
        // 获取主辅仪器使用前后的列表
        getUsecheck(obj) {
            obj.use = [];
            var data = {
                id: obj.id
            }
            this.$http({
                method: 'post',
                apiUrl: '/resource/readPreUsecheckList.htm',
                params: data,
                isJson: false,
            }).then(res => {
                if (res.code === 0) {

                    for (var i in res.data) {
                        this.$set(res.data[i], 'doPass', null);
                    }
                    obj.before = res.data;
                }
            })
            var data1 = {
                id: obj.id,
                checkType:1
            }
            // checkType:1
            this.$http({
                method: 'post',
                apiUrl: '/resource/readUsecheckList.htm',
                params: data1,
                isJson: false,
            }).then(res => {
                if (res.code === 0) {
                    for (var i in res.data) {
                        this.$set(res.data[i], 'doPass', null);
                    }
                    obj.after = res.data;
                }
            })
        },
        // 读取使用记录
        readEquipmentUse(obj) {
             return new Promise((resolve, reject) => {
                 this.$http({
                    method: 'post',
                    apiUrl: '/resource/readEquipmentUse.htm',
                    params: {
                        fRef: obj.id,
                        batch: this.testpanelData.id
                    },
                    isJson: false,
                }).then(res => {
                if (res.code == 0) {
                        resolve(res)
                    }else{
                        reject(err)
                    }
                })
             });
            // var url = "/resource/readEquipmentUse.htm"
            // var obj = {
            //     fRef: obj.id,
            //     batch: this.testpanelData.id
            // }
            // this.$commitHttp(url,obj,{success : function(data) {
            //     if (res.code == 0) {
            //         resolve(res)
            //     }else{
            //         reject(err)
            //     }
            // }},false),

        },


        // 是否重新加载
        reLoad() {
            this.reload = false;
            this.$nextTick(() => {
                this.reload = true;
            })
        },
        // 高亮显示
        lightHight() {
            // 使用前检查项，选中的id和查看仪器检查项的ids对比 一致则高亮显示
            this.$nextTick(() => {
                for (var i in this.equipPreUseList) {
                    if (this.equipPreUseList[i].ids != undefined) {
                        this.$refs.multipleTable.toggleRowSelection(this.equipPreUseList[i], true)
                    }
                }
            })
            this.$nextTick(() => { //对比使用后检查项
                for (var i in this.equipUseList) {
                    if (this.equipUseList[i].ids != undefined) {
                        this.$refs.multipleTable1.toggleRowSelection(this.equipUseList[i], true)
                    }
                }
            })

        },
        // 提交
        subEquipInfo() {
            console.log(this.equipArr)
            var data = []
            for(var i in this.equipArr){
                var obj = {};
                obj.fRef = this.equipArr[i].id;
                obj.batch = this.testpanelData.id;
                obj.isMain = this.equipArr[i].isMain;
                // obj.equipInfo = {};
                obj.useBeans = [];
                obj.beforeBeans = [];
                obj.afterBeans = [];
                if(this.equipArr[i].before.length != 0 || this.equipArr[i].after.length != 0){
                    if(this.equipArr[i].use.length == 0){
                        this.$notify({
                            type: 'warning',
                            title: '警告',
                            message: '"' + this.equipArr[i].name  + '"' + '请添加仪器使用记录！'
                        })
                        return;
                    }
                }
                for(var j in this.equipArr[i].use){ //仪器使用记录不能为空
                    var useRecord = this.equipArr[i].use[j]
                    if (useRecord.temperature == undefined  || useRecord.temperature == null || useRecord.temperature == ''
                    || useRecord.humidity == undefined || useRecord.humidity == null || useRecord.humidity == ''
                    || useRecord.runStatus == undefined || useRecord.runStatus == null || useRecord.runStatus == ''
                    || useRecord.startDate == undefined || useRecord.startDate == null || useRecord.startDate == ''
                    || useRecord.endDate == undefined || useRecord.endDate == null || useRecord.endDate == '') {
                        this.$notify({
                            type: 'warning',
                            title: '警告',
                            message: '"' + this.equipArr[i].name  + '"' + '请填写完整仪器使用记录！'
                        })
                        return;
                    }
                    var startDate = new Date(useRecord.startDate).getTime();
                    var endDate = new Date(useRecord.endDate).getTime();
                    if (startDate > endDate) {
                        this.$notify({
                            type: 'warning',
                            title: '警告',
                            message:'"' + this.equipArr[i].name  + '"' + '关机时间要大于开机时间'
                        })
                        return;
                    }
                }
                obj.useBeans = this.equipArr[i].use
                var preUseSelection = [];
                for(var j in this.equipArr[i].before){ //仪器使用记录不能为空
                    var beforeRecord = this.equipArr[i].before[j];
                    if (beforeRecord.doPass !== null && beforeRecord.doPass !== undefined && beforeRecord.doPass !== '') {
                        beforeRecord.fRef = this.equipArr[i].id;
                        beforeRecord.batch = this.testpanelData.id;
                        preUseSelection.push(beforeRecord)
                    }
                }
                obj.beforeBeans = preUseSelection

                var afterUseSelection = [];
                for (var j in this.equipArr[i].after) {
                    var afterRecord = this.equipArr[i].after[j];
                    if (afterRecord.doPass !== null && afterRecord.doPass !== undefined && afterRecord.doPass !== "") {
                        afterRecord.fRef = this.equipArr[i].id;
                        afterRecord.batch = this.testpanelData.id;
                        afterUseSelection.push(afterRecord)
                    }
                }
                console.log(afterUseSelection)
                obj.afterBeans = afterUseSelection
                data.push(obj)
            }

            if (this.editOrAdd == 'add') {
                var url = "/resource/addEquipmentUse.htm"
            } else {
                var url = "/resource/updateEquipmentUse.htm"
                // data.id = this.equipForm.id;
            }
            this.isRepeat = false;
            this.$http({
                method: 'post',
                apiUrl: url,
                params: data,
                isJson: true,
                isLoading:true
            }).then(res => {
               this.isRepeat = true;
                if (res.code === 0) {
                    this.$notify({
                        title: '成功',
                        type: 'success',
                        message: '保存成功'
                    });
                    this.$emit('hasEquipUseChange', true)
                    this.close();

                }
            })
        },

        //关闭
        close(formName) {
            this.$emit('update:addVisible', false);
            this.equipForm = {
                startDate: "",
                endDate: "",
                temperature: "",
                humidity: "",
                runStatus: "",
            };
            this.equipArr = [];
        },
        getEuitpmentTemp(row,item) {
         
            console.log(row,item)
            for (var i in row) {
                this.rowTime[i] = row[i];
            }
            var startDate = new Date(this.rowTime.startDate).getTime();
            var endDate = new Date(this.rowTime.endDate).getTime();
            if (startDate > endDate) {
                this.$notify({
                    type: 'warning',
                    title: '警告',
                    message: '关机时间要大于开机时间'
                })
                return;
            }
             this.equipmentId = item.id
            this.equiptempShow = true;
        },

    }
}
</script>

<style scoped>

</style><style>
.equipCheckDialog .el-dialog {
    margin-top: 7vh !important;
    height: 85%;
}

.equipCheckDialog .el-dialog .el-dialog__body {
    height: calc(100% - 85px);
    padding: 10px;
}
.checkDialog.equipCheckDialog .el-dialog .el-dialog__body{
     height: calc(100% - 45px);
    padding: 10px;
}

.equipCheckDialog .equipUseRecord .el-form-item {
    width: 49%;
    float: left;
    margin-bottom: 8px;
}

.equipCheckDialog .equipform {
    height: 150px;
}
.equipCheckDialog .el-tabs{
	height:100%;
}
.equipCheckDialog .el-tabs__content{
	height:calc(100% - 50px);
}
.equipCheckDialog .el-tabs__content .el-tab-pane{
	height:100%;
}

.equipCheckDialog .equipTable {
    height: calc(100% - 145px);
    clear: both;
}

.startAndEnd .el-time-panel {
    width: 180px;
}



/*最后一列秒隐藏*/

.startAndEnd .el-time-panel .el-time-panel__content .el-time-spinner .el-time-spinner__wrapper.el-scrollbar:nth-last-child(0) {
    display: none;
}
</style>
